﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Password_Manager
{

    internal class Generated
    {

        // 字符集配置
        private readonly string numericCharSet = "0123456789";
        private readonly string alphanumericCharSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        public string GenerateNumericPassword(int length)
        {
            if (length <= 0)
                throw new ArgumentException("长度必须大于0", nameof(length));

            using (var rng = RandomNumberGenerator.Create())
            {
                var result = new StringBuilder(length);
                var buffer = new byte[4];

                for (int i = 0; i < length; i++)
                {
                    rng.GetBytes(buffer);
                    uint random = BitConverter.ToUInt32(buffer, 0);
                    int index = (int)(random % (uint)numericCharSet.Length);
                    result.Append(numericCharSet[index]);
                }

                return result.ToString();
            }
        }

        public string GenerateAlphanumericPassword(int length)
        {
            if (length <= 0)
                throw new ArgumentException("长度必须大于0", nameof(length));

            using (var rng = RandomNumberGenerator.Create())
            {
                var result = new StringBuilder(length);
                var buffer = new byte[4];

                for (int i = 0; i < length; i++)
                {
                    rng.GetBytes(buffer);
                    uint random = BitConverter.ToUInt32(buffer, 0);
                    int index = (int)(random % (uint)alphanumericCharSet.Length);
                    result.Append(alphanumericCharSet[index]);
                }

                return result.ToString();
            }
        }
    }
}
